package com.genebio.equinox.update;

import javax.servlet.Servlet;
import javax.servlet.ServletException;

import org.eclipse.equinox.http.helper.BundleEntryHttpContext;
import org.eclipse.equinox.http.helper.ContextPathServletAdaptor;
import org.osgi.service.http.HttpContext;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpService;
import org.osgi.util.tracker.ServiceTracker;

import com.genebio.equinox.update.servlets.ListFeatures;
import com.genebio.equinox.update.servlets.SearchFeatures;

public class UpdateActivation implements BundleActivator {


	public final static String ROOT="/features";

	private HttpServiceTracker httpServiceTracker;

	public void start(BundleContext context) throws Exception {
		httpServiceTracker = new HttpServiceTracker(context);
		httpServiceTracker.open();
	}

	public void stop(BundleContext context) throws Exception {
		httpServiceTracker.close();
	}

	private class HttpServiceTracker extends ServiceTracker {

		public HttpServiceTracker(BundleContext context) {
			super(context, HttpService.class.getName(), null);
		}

		public Object addingService(ServiceReference reference) {
			final HttpService httpService = (HttpService) context.getService(reference);
			HttpContext commonContext = (HttpContext) new BundleEntryHttpContext(context.getBundle(), "/");

			Servlet adaptedServlet = new ContextPathServletAdaptor(new ListFeatures(), ROOT);
					
			//register root jsp pages + springcontext listener
			try {
				httpService.registerServlet(ROOT+"/list", new ListFeatures(), null, commonContext);
				httpService.registerServlet(ROOT+"/info", new SearchFeatures(), null, commonContext);
			} catch (Exception e) {
				e.printStackTrace();
			}
					
			return httpService;
		}

		public void removedService(ServiceReference reference, Object service) {
			final HttpService httpService = (HttpService) service;
			httpService.unregister(ROOT+"/list");
			httpService.unregister(ROOT+"/info");
			super.removedService(reference, service);
		}			
	}

}
